package com.jack.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 四数之和 {

    public static void main(String[] args) {
        int[] nums = {1, 0, -1, 0, -2, 2};
        List<List<Integer>> lists = fourSum(nums, 0);
        lists.forEach(l -> {
            l.forEach(s -> System.out.print(s + ","));
            System.out.println();
        });

        int[] nums1 = {-1, 0, -5, -2, -2, -4, 0, 1, -2};
        fourSum(nums1, -9).forEach(l -> {
            l.forEach(s -> System.out.print(s + ","));
            System.out.println();
        });
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        if (n < 4) {
            return result;
        }
        Arrays.sort(nums);
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            if (nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target) {
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int k = j + 1;
                int h = n - 1;
                if (nums[i] + nums[j] + nums[k] + nums[k + 1] > target) {
                    continue;
                }
                if (nums[i] + nums[j] + nums[h - 1] + nums[h] < target) {
                    continue;
                }
                while (k < h) {
                    int cur = nums[i] + nums[j] + nums[k] + nums[h];
                    if (cur == target) {
                        result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[h]));
                        k++;
                        while (k < h && nums[k] == nums[k - 1]) {
                            k++;
                        }
                        h--;
                        while (k < h && nums[h] == nums[h + 1]) {
                            h--;
                        }
                    } else if (cur > target) {
                        h--;
                    } else {
                        k++;
                    }
                }
            }
        }
        return result;
    }
}
